<template>
  <div class="transaction-history">
    <NavBar />
    <main class="container">
      <h1>我的订单记录</h1>
      
      <div class="tabs">
        <button 
          class="tab-btn" 
          :class="{ active: activeTab === 'all' }"
          @click="changeTab('all')"
        >
          全部订单
        </button>
        <button 
          class="tab-btn" 
          :class="{ active: activeTab === 'pending' }"
          @click="changeTab('pending')"
        >
          待处理
        </button>
        <button 
          class="tab-btn" 
          :class="{ active: activeTab === 'completed' }"
          @click="changeTab('completed')"
        >
          已完成
        </button>
        <button 
          class="tab-btn" 
          :class="{ active: activeTab === 'cancelled' }"
          @click="changeTab('cancelled')"
        >
          已取消
        </button>
      </div>
      
      <LoadingSpinner v-if="isLoading" message="正在加载订单数据..." />
      
      <div class="transactions-list" v-else-if="transactions.length > 0">
        <div 
          class="transaction-card"
          v-for="transaction in transactions"
          :key="transaction.id"
        >
          <div class="transaction-header">
            <div class="transaction-id">订单号: {{ transaction.order_id }}</div>
            <div class="transaction-status" :class="getStatusClass(transaction.status)">
              {{ getStatusText(transaction.status) }}
            </div>
          </div>
          
          <div class="transaction-content">
            <div class="transaction-details">
              <div class="detail-item">
                <span class="label">订单ID:</span>
                <span>{{ transaction.id }}</span>
              </div>
              <div class="detail-item">
                <span class="label">创建时间:</span>
                <span>{{ formatDateTime(transaction.created_at) }}</span>
              </div>
              <div class="detail-item">
                <span class="label">更新时间:</span>
                <span>{{ formatDateTime(transaction.updated_at) }}</span>
              </div>
            </div>
            
            <div class="transaction-actions">
              <button 
                v-if="transaction.status === 'pending'"
                class="btn-confirm"
                @click="goToPayment(transaction.order_id)"
              >
                支付订单
              </button>
              <button 
                v-if="transaction.status === 'pending'"
                class="btn-cancel"
                @click="cancelTransaction(transaction.order_id)"
              >
                取消订单
              </button>
              <button 
                v-if="transaction.status === 'completed' && !transaction.hasRated"
                class="btn-rate"
                @click="rateTransaction(transaction.id)"
              >
                评价
              </button>
              <button 
                v-if="transaction.status === 'completed' && transaction.hasRated"
                class="btn-view-rate"
                @click="viewRating(transaction.id)"
              >
                查看评价
              </button>
              <button 
                class="btn-detail"
                @click="viewOrderDetail(transaction.order_id)"
              >
                查看详情
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <div class="empty-state" v-else>
        <div class="empty-icon">📝</div>
        <h3>暂无订单记录</h3>
        <p v-if="activeTab !== 'all'">试试查看"全部订单"</p>
        <p v-else>快去浏览书籍，开始你的第一笔交易吧！</p>
        <router-link to="/" class="btn-browse">浏览书籍</router-link>
      </div>
      
      <!-- 评价弹窗 -->
      <div class="rating-modal" v-if="showRatingModal">
        <div class="modal-content">
          <div class="modal-header">
            <h3>交易评价</h3>
            <button class="close-btn" @click="showRatingModal = false">×</button>
          </div>
          <div class="modal-body">
            <div class="rating-book-info">
              <h4>订单 #{{ currentRatingOrder }}</h4>
            </div>
            
            <div class="rating-stars">
              <span>评分:</span>
              <div class="stars-container">
                <span 
                  v-for="i in 5" 
                  :key="i" 
                  class="star" 
                  :class="{ active: rating >= i }"
                  @click="rating = i"
                >★</span>
              </div>
            </div>
            
            <div class="form-group">
              <label for="rating-comment">评价内容:</label>
              <textarea 
                id="rating-comment" 
                v-model="ratingComment" 
                rows="4" 
                placeholder="请分享您对这次交易的评价..."
              ></textarea>
            </div>
            
            <div class="modal-actions">
              <button class="btn-submit" @click="submitRating">提交评价</button>
              <button class="btn-cancel" @click="showRatingModal = false">取消</button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 订单详情弹窗 -->
      <div class="order-detail-modal" v-if="showOrderDetailModal">
        <div class="modal-content">
          <div class="modal-header">
            <h3>订单详情</h3>
            <button class="close-btn" @click="showOrderDetailModal = false">×</button>
          </div>
          <div class="modal-body">
            <LoadingSpinner v-if="isLoadingDetail" message="加载订单详情..." />
            
            <div v-else-if="orderDetail" class="order-detail-content">
              <!-- 如果book是数组，遍历显示 -->
              <div v-if="orderDetail.book && Array.isArray(orderDetail.book) && orderDetail.book.length > 0">
                <h3>图书信息</h3>
                <div v-for="(book, index) in orderDetail.book" :key="index" class="order-book-item">
                  <div class="order-book-header">
                    <h4>{{ book.title || '未知书名' }}</h4>
                    <div class="order-book-price">¥{{ book.price || 0 }}</div>
                  </div>
                  
                  <div class="order-book-info">
                    <div class="info-item">
                      <span class="label">作者:</span>
                      <span>{{ book.author || '未知' }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">卖家:</span>
                      <span>{{ book.seller || book.sellerName || '未知' }}</span>
                    </div>
                    <div class="info-item" v-if="book.department">
                      <span class="label">学院:</span>
                      <span>{{ book.department }}</span>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 如果book是单个对象，直接显示 -->
              <div v-else-if="orderDetail.book && !Array.isArray(orderDetail.book)" class="order-books-list">
                <h3>图书信息</h3>
                <div class="order-book-item">
                  <div class="order-book-header">
                    <h4>{{ orderDetail.book.title || '未知书名' }}</h4>
                    <div class="order-book-price">¥{{ orderDetail.book.price || 0 }}</div>
                  </div>
                  
                  <div class="order-book-info">
                    <div class="info-item">
                      <span class="label">作者:</span>
                      <span>{{ orderDetail.book.author || '未知' }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">卖家:</span>
                      <span>{{ orderDetail.book.seller || orderDetail.book.sellerName || '未知' }}</span>
                    </div>
                    <div class="info-item" v-if="orderDetail.book.department">
                      <span class="label">学院:</span>
                      <span>{{ orderDetail.book.department }}</span>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 如果books属性存在（可能是另一种命名） -->
              <div v-else-if="orderDetail.books && Array.isArray(orderDetail.books) && orderDetail.books.length > 0" class="order-books-list">
                <h3>图书信息</h3>
                <div v-for="(book, index) in orderDetail.books" :key="index" class="order-book-item">
                  <div class="order-book-header">
                    <h4>{{ book.title || '未知书名' }}</h4>
                    <div class="order-book-price">¥{{ book.price || 0 }}</div>
                  </div>
                  
                  <div class="order-book-info">
                    <div class="info-item">
                      <span class="label">作者:</span>
                      <span>{{ book.author || '未知' }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">卖家:</span>
                      <span>{{ book.seller || book.sellerName || '未知' }}</span>
                    </div>
                    <div class="info-item" v-if="book.department">
                      <span class="label">学院:</span>
                      <span>{{ book.department }}</span>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 无图书信息情况 -->
              <div v-else class="no-book-info">
                <p>暂无图书详情信息</p>
              </div>
            </div>
            
            <div v-else class="empty-order-detail">
              <p>暂无订单详情数据</p>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 支付模态框 -->
      <div class="payment-modal" v-if="showPaymentModal">
        <div class="modal-content">
          <div class="modal-header">
            <h3>订单支付</h3>
            <button class="close-btn" @click="showPaymentModal = false">×</button>
          </div>
          <div class="modal-body">
            <div class="payment-order-info">
              <h4>订单号: {{ currentPayOrder }}</h4>
              <div class="payment-amount">应付金额: ¥{{ currentPayAmount || '计算中...' }}</div>
            </div>
            
            <div class="payment-methods">
              <h4>选择支付方式</h4>
              <div class="payment-method-options">
                <div 
                  class="payment-method-option" 
                  :class="{ active: selectedPaymentMethod === 'wechat' }"
                  @click="selectedPaymentMethod = 'wechat'"
                >
                  <img src="@/assets/wxpay.png" alt="微信支付" class="payment-icon">
                  <span>微信支付</span>
                </div>
                <div 
                  class="payment-method-option" 
                  :class="{ active: selectedPaymentMethod === 'alipay' }"
                  @click="selectedPaymentMethod = 'alipay'"
                >
                  <img src="@/assets/alipay.png" alt="支付宝" class="payment-icon">
                  <span>支付宝</span>
                </div>
              </div>
            </div>
            
            <div class="payment-remark">
              <h4>备注信息 (选填)</h4>
              <textarea 
                v-model="paymentRemark" 
                placeholder="填写支付备注信息..."
                rows="3"
              ></textarea>
            </div>
            
            <div class="payment-actions">
              <button 
                class="btn-pay-submit" 
                :disabled="!selectedPaymentMethod || isProcessingPayment"
                @click="processPayment"
              >
                {{ isProcessingPayment ? '处理中...' : '立即支付' }}
              </button>
              <button class="btn-pay-cancel" @click="showPaymentModal = false">取消</button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 取消订单确认模态框 -->
      <div class="cancel-confirm-modal" v-if="showCancelConfirmModal">
        <div class="modal-content">
          <div class="modal-header">
            <h3>取消订单</h3>
            <button class="close-btn" @click="showCancelConfirmModal = false">×</button>
          </div>
          <div class="modal-body">
            <div class="cancel-warning">
              <el-icon><WarningFilled /></el-icon>
              <p>您确定要取消订单 <span class="order-id-highlight">#{{ currentCancelOrderId }}</span> 吗？</p>
            </div>
            <p class="cancel-notice">取消后，该书籍将重新上架，您需要重新下单购买</p>
            
            <div class="cancel-actions">
              <button class="btn-confirm-cancel" @click="confirmCancelOrder">确认取消</button>
              <button class="btn-abort-cancel" @click="showCancelConfirmModal = false">我再想想</button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 查看评价模态框 -->
      <div class="rating-view-modal" v-if="showRatingViewModal">
        <div class="modal-content">
          <div class="modal-header">
            <h3>评价详情</h3>
            <button class="close-btn" @click="showRatingViewModal = false">×</button>
          </div>
          <div class="modal-body">
            <LoadingSpinner v-if="isLoadingRating" message="加载评价..." />
            
            <div v-else-if="currentRatingData" class="rating-detail">
              <div class="rating-stars-display">
                <span>评分:</span>
                <div class="stars-container">
                  <span 
                    v-for="i in 5" 
                    :key="i" 
                    class="star" 
                    :class="{ active: currentRatingData.score >= i }"
                  >★</span>
                </div>
              </div>
              
              <div class="rating-comment-box">
                <h4>评价内容</h4>
                <p>{{ currentRatingData.comment }}</p>
              </div>
              
              <div class="rating-metadata">
                <div class="rating-time">评价时间: {{ formatDateTime(currentRatingData.created_at) }}</div>
              </div>
            </div>
            
            <div v-else class="empty-rating">
              <p>暂无评价数据或评价已被删除</p>
            </div>
            
            <div class="modal-actions">
              <button class="btn-close" @click="showRatingViewModal = false">关闭</button>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import NavBar from '../components/NavBar.vue'
import LoadingSpinner from '../components/LoadingSpinner.vue'
import api from '@/api/apiClient'
import { ElMessage } from 'element-plus'
import { WarningFilled } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const activeTab = ref('all')
const transactions = ref([])
const isLoading = ref(true)
const showRatingModal = ref(false)
const currentRatingOrder = ref(null)
const rating = ref(5)
const ratingComment = ref('')

// 评价数据相关
const userRatings = ref([])
const hasLoadedRatings = ref(false)

// 订单详情相关
const showOrderDetailModal = ref(false)
const isLoadingDetail = ref(false)
const orderDetail = ref(null)
const currentOrderId = ref(null)

// 支付相关
const showPaymentModal = ref(false)
const currentPayOrder = ref(null)
const currentPayAmount = ref(null)
const selectedPaymentMethod = ref('')
const paymentRemark = ref('')
const isProcessingPayment = ref(false)

// 取消订单相关
const showCancelConfirmModal = ref(false)
const currentCancelOrderId = ref(null)

// 添加查看评价相关的状态
const showRatingViewModal = ref(false)
const isLoadingRating = ref(false)
const currentRatingData = ref(null)
const currentRatingTransactionId = ref(null)

// 获取交易记录
onMounted(() => {
  fetchTransactions()
  fetchUserRatings() // 获取用户评价数据
  
  // 检查localStorage中是否有待支付的订单
  const pendingOrderId = localStorage.getItem('currentPayOrderId')
  
  if (pendingOrderId) {
    console.log('检测到待支付订单，自动打开支付对话框，订单ID:', pendingOrderId)
    
    // 设置一个短暂的延迟，确保订单列表已加载
  setTimeout(() => {
      goToPayment(pendingOrderId)
      // 清除localStorage中的订单ID
      localStorage.removeItem('currentPayOrderId')
    }, 1500)
    
    // 显示提示信息
    ElMessage.info('正在准备支付页面，请稍候...')
  }
})

const changeTab = (tab) => {
  activeTab.value = tab
  fetchTransactions(tab !== 'all' ? tab : null)
}

const fetchTransactions = async (status = null) => {
  try {
    isLoading.value = true
    
    // 构建请求参数
    const params = {}
    if (status) {
      params.status = status
    }
    
    // 调用API获取订单数据
    const response = await api.orders.getAll(params)
    console.log('获取到的原始响应:', response)
    
    // 处理响应数据 - 直接检查response对象
    if (response && response.orders && Array.isArray(response.orders)) {
      // 直接使用response.orders
      transactions.value = response.orders
      console.log('获取订单数据成功:', transactions.value)
      
      // 如果已经获取了评价数据，则更新订单评价状态
      if (hasLoadedRatings.value) {
        updateTransactionsRatingStatus()
      }
    } else {
      // 尝试其他可能的数据结构
      if (response && response.data && response.data.orders && Array.isArray(response.data.orders)) {
        transactions.value = response.data.orders
        console.log('通过data.orders获取数据成功:', transactions.value)
        
        // 如果已经获取了评价数据，则更新订单评价状态
        if (hasLoadedRatings.value) {
          updateTransactionsRatingStatus()
        }
      } else {
        console.warn('未能找到有效的订单数据', response)
        transactions.value = []
      }
    }
  } catch (error) {
    console.error('获取订单数据失败:', error)
    ElMessage.error('获取订单数据失败，请稍后重试')
    transactions.value = []
  } finally {
    isLoading.value = false
  }
}

const getStatusClass = (status) => {
  const statusClassMap = {
    'pending': 'pending',
    'completed': 'completed',
    'cancelled': 'cancelled',
    'processing': 'pending',
    'delivered': 'completed',
    'refunded': 'cancelled'
  }
  return statusClassMap[status] || 'pending'
}

const getStatusText = (status) => {
  const statusMap = {
    'pending': '待处理',
    'processing': '处理中',
    'delivered': '已发货',
    'completed': '已完成',
    'cancelled': '已取消',
    'refunded': '已退款'
  }
  return statusMap[status] || status
}

const formatDateTime = (dateString) => {
  if (!dateString) return '未知时间';
  
  try {
    const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
    });
  } catch (error) {
    console.error('日期格式化错误:', error);
    return dateString;
  }
}

const confirmTransaction = async (orderId) => {
  try {
    if (confirm('确认完成此订单？')) {
      isLoading.value = true
      await api.orders.confirm(orderId)
      ElMessage.success('订单确认成功')
      fetchTransactions(activeTab.value !== 'all' ? activeTab.value : null)
    }
  } catch (error) {
    console.error('确认订单失败:', error)
    ElMessage.error('确认订单失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

// 修改支付方法，使用模态框
const goToPayment = async (orderId) => {
  try {
    // 直接显示支付对话框，不再请求订单详情
    console.log('准备支付订单:', orderId);
    
    // 设置当前支付订单ID
    currentPayOrder.value = orderId;
    
    // 由于无法获取订单金额，设置一个提示文本
    currentPayAmount.value = '以实际扣款为准';
    
    // 重置支付表单
    selectedPaymentMethod.value = 'wechat';
    paymentRemark.value = '';
    
    // 显示支付模态框
    showPaymentModal.value = true;
    isLoading.value = false;
  } catch (error) {
    console.error('准备支付失败:', error);
    ElMessage.error('准备支付失败，请稍后重试');
    isLoading.value = false;
  }
}

// 处理支付提交
const processPayment = async () => {
  try {
    isProcessingPayment.value = true
    
    // 确保订单ID是字符串
    const orderId = typeof currentPayOrder.value === 'object' 
      ? currentPayOrder.value.order_id 
      : currentPayOrder.value;
    
    if (!orderId) {
      ElMessage.error('订单ID不存在，无法支付');
      isProcessingPayment.value = false;
      return;
    }
    
    console.log('正在支付订单:', orderId);
    
    // 构建支付数据，只需要订单ID
    const paymentData = {
      order_id: orderId
    }
    
    // 调用支付API
    const response = await api.orders.pay(paymentData)
    
    // 检查响应
    if (response && response.code !== undefined) {
      if (response.code !== 200) {
        throw new Error(response.message || '支付处理失败')
      }
    }
    
    ElMessage.success('支付成功！')
    showPaymentModal.value = false
    
    // 刷新订单列表
    setTimeout(() => {
      fetchTransactions(activeTab.value !== 'all' ? activeTab.value : null)
    }, 1000)
  } catch (error) {
    console.error('支付失败:', error)
    
    // 提取更详细的错误信息
    let errorMessage = '支付处理失败，请稍后重试'
    
    // 如果是服务器返回的错误信息
    if (error.response && error.response.data) {
      if (error.response.data.message) {
        errorMessage = error.response.data.message
      } else if (error.response.data.error) {
        errorMessage = error.response.data.error
      }
    } 
    // 如果是我们自己抛出的带有message的Error
    else if (error.message) {
      errorMessage = error.message
    }
    
    // 添加用户友好的提示
    if (errorMessage.includes('余额不足')) {
      errorMessage += '，请前往个人中心充值'
    } else if (errorMessage.includes('订单不存在') || errorMessage.includes('未找到订单')) {
      errorMessage += '，请刷新页面查看最新订单状态'
      // 关闭支付模态框，让用户看到刷新后的订单列表
      showPaymentModal.value = false
      // 延迟刷新订单列表
      setTimeout(() => {
        fetchTransactions(activeTab.value !== 'all' ? activeTab.value : null)
      }, 500)
    }
    
    ElMessage.error(errorMessage)
  } finally {
    isProcessingPayment.value = false
  }
}

// 修改取消订单方法，使用模态框
const cancelTransaction = (orderId) => {
  currentCancelOrderId.value = orderId
  showCancelConfirmModal.value = true
}

// 确认取消订单
const confirmCancelOrder = async () => {
  try {
    isLoading.value = true
    await api.orders.cancel(currentCancelOrderId.value)
    
    // 清除本地存储中的订单信息
    localStorage.removeItem('pendingOrderData')
    localStorage.removeItem('currentPayOrderId')
    
    ElMessage.success('订单取消成功')
    showCancelConfirmModal.value = false
    
    // 刷新页面，确保所有状态重置
    setTimeout(() => {
      window.location.reload()
    }, 1000)
  } catch (error) {
    console.error('取消订单失败:', error)
    ElMessage.error('取消订单失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

const rateTransaction = (transactionId) => {
  // 设置当前评价交易ID
  currentRatingOrder.value = transactionId
  
  // 重置评价表单
  rating.value = 5
  ratingComment.value = ''
  
  console.log('准备评价交易ID:', transactionId)
  
  // 显示评价弹窗
  showRatingModal.value = true
}

// 获取用户评价数据
const fetchUserRatings = async () => {
  try {
    console.log('获取用户所有评价数据')
    
    // 调用API获取所有评价
    const response = await api.rating.getAll()
    
    console.log('获取评价响应:', response)
    
    // 处理响应数据
    if (response && response.ratings && Array.isArray(response.ratings)) {
      userRatings.value = response.ratings
      console.log('已加载用户评价数据:', userRatings.value.length, '条')
    } else if (response && response.data && response.data.ratings && Array.isArray(response.data.ratings)) {
      userRatings.value = response.data.ratings
      console.log('已加载用户评价数据(data.ratings):', userRatings.value.length, '条')
    } else {
      console.warn('获取评价数据格式不正确', response)
      userRatings.value = []
    }
    
    hasLoadedRatings.value = true
    
    // 更新订单列表中的评价状态
    updateTransactionsRatingStatus()
  } catch (error) {
    console.error('获取用户评价数据失败:', error)
    userRatings.value = []
    hasLoadedRatings.value = true
  }
}

// 更新订单列表中的评价状态
const updateTransactionsRatingStatus = () => {
  if (!transactions.value.length || !userRatings.value.length) return
  
  console.log('更新订单评价状态')
  
  transactions.value.forEach(transaction => {
    // 检查该交易是否有评价
    const hasRating = userRatings.value.some(rating => 
      rating.transaction_id === transaction.id
    )
    
    // 添加hasRated属性
    transaction.hasRated = hasRating
    
    if (hasRating) {
      console.log(`订单 ${transaction.id} 已评价`)
    }
  })
}

// 提交评价成功后更新本地数据和UI
const submitRating = async () => {
  try {
    if (!rating.value || !currentRatingOrder.value) {
      ElMessage.warning('请选择评分');
      return;
    }
    
    if (!ratingComment.value.trim()) {
      ElMessage.warning('请填写评价内容');
      return;
    }
    
    console.log('提交评价: 交易ID=', currentRatingOrder.value, '评分=', rating.value, '评价=', ratingComment.value);
    
    // 确保交易ID是整数
    const transactionId = parseInt(currentRatingOrder.value);
    if (isNaN(transactionId)) {
      ElMessage.error('交易ID无效，无法提交评价');
      return;
    }
    
    // 构造评价数据
    const ratingData = {
      transaction_id: transactionId,
      score: rating.value,
      comment: ratingComment.value.trim()
    };
    
    console.log('发送评价数据:', ratingData);
    
    // 调用API提交评价
    const response = await api.rating.create(ratingData);
    
    console.log('评价API响应:', response);
    
    // 评价成功，更新本地数据
    const newRating = {
      transaction_id: transactionId,
      score: rating.value,
      comment: ratingComment.value.trim(),
      created_at: new Date().toISOString()
    };
    
    // 添加到本地评价列表
    userRatings.value.push(newRating);
    
    // 更新交易状态
    const targetTransaction = transactions.value.find(t => t.id === transactionId);
    if (targetTransaction) {
      targetTransaction.hasRated = true;
    }
    
    ElMessage.success('评价提交成功！感谢您的反馈。');
    showRatingModal.value = false;
    rating.value = 5;
    ratingComment.value = '';
    
    // 刷新订单列表
    setTimeout(() => {
      fetchTransactions(activeTab.value !== 'all' ? activeTab.value : null);
    }, 500);
  } catch (error) {
    console.error('提交评价失败:', error);
    
    // 提取错误信息
    let errorMessage = '提交评价失败，请稍后重试';
    if (error.response && error.response.data && error.response.data.message) {
      errorMessage = error.response.data.message;
    } else if (error.message) {
      errorMessage = error.message;
    }
    
    ElMessage.error(errorMessage);
  }
}

const viewOrderDetail = async (orderId) => {
  try {
    isLoadingDetail.value = true;
    showOrderDetailModal.value = true;
    currentOrderId.value = orderId;
    
    console.log('获取订单详情，订单ID:', orderId);
    
    // 使用API获取订单详情
    const response = await api.orders.getDetail(orderId);
    
    console.log('订单详情API响应:', response);
    
    if (response) {
      // 检查返回的订单对象是否有效 - 使用response.data作为我们的数据源
      if (response.code === 200 && response.data) {
        // API成功返回了数据
        orderDetail.value = response.data;
        console.log('成功获取订单详情(API):', orderDetail.value);
      } else if (response.book) {
        // 有些API直接返回book数组的情况
        orderDetail.value = response;
        console.log('成功获取订单详情(直接book):', orderDetail.value);
      } else {
        // API返回的数据不包含有效信息，尝试从当前列表获取
        const currentOrder = transactions.value.find(t => t.order_id === orderId);
        if (currentOrder) {
          orderDetail.value = currentOrder;
          console.log('从当前列表获取订单详情:', orderDetail.value);
        } else {
          // 无法获取详情，显示基本信息
          orderDetail.value = { order_id: orderId };
          ElMessage.warning('无法获取详细订单信息');
        }
      }
    } else {
      // API调用返回为空，尝试从当前列表获取
      const currentOrder = transactions.value.find(t => t.order_id === orderId);
      if (currentOrder) {
        orderDetail.value = currentOrder;
        console.log('从当前列表获取订单详情(API无响应):', orderDetail.value);
      } else {
        // 无法获取详情，显示基本信息
        orderDetail.value = { order_id: orderId };
        ElMessage.warning('无法获取详细订单信息');
      }
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    
    // 发生错误时，尝试从当前列表获取数据作为备选方案
    const currentOrder = transactions.value.find(t => t.order_id === orderId);
    if (currentOrder) {
      orderDetail.value = currentOrder;
      console.log('API错误，从当前列表获取订单详情:', orderDetail.value);
    } else {
      orderDetail.value = { order_id: orderId };
      ElMessage.error('获取订单详情失败，请稍后重试');
    }
  } finally {
    isLoadingDetail.value = false;
  }
}

// 查看评价详情
const viewRating = async (transactionId) => {
  try {
    showRatingViewModal.value = true
    isLoadingRating.value = true
    currentRatingTransactionId.value = transactionId
    
    console.log('查看交易评价:', transactionId)
    
    // 首先检查本地已加载的评价数据
    const existingRating = userRatings.value.find(r => r.transaction_id === transactionId)
    
    if (existingRating) {
      console.log('使用本地评价数据:', existingRating)
      currentRatingData.value = existingRating
      isLoadingRating.value = false
      return
    }
    
    // 如果本地没有，则调用API获取
    const response = await api.rating.getByTransaction(transactionId)
    
    console.log('获取评价响应:', response)
    
    // 处理响应数据
    if (response) {
      // 检查不同的响应结构
      if (response.code === 200 && response.data) {
        // 直接使用响应中的rating对象
        currentRatingData.value = response.data
      } else if (response.code === 200) {
        // 可能rating直接在response中
        currentRatingData.value = response
      } else {
        // 尝试其他可能的数据结构
        currentRatingData.value = null
        ElMessage.warning('评价数据格式不正确')
      }
    } else {
      currentRatingData.value = null
      ElMessage.warning('未找到该交易的评价')
    }
  } catch (error) {
    console.error('获取评价详情失败:', error)
    currentRatingData.value = null
    
    // 提取错误信息
    let errorMessage = '获取评价详情失败'
    if (error.response && error.response.data && error.response.data.message) {
      errorMessage = error.response.data.message
    } else if (error.message) {
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
  } finally {
    isLoadingRating.value = false
  }
}
</script>

<style scoped>
.container {
  max-width: 900px;
  margin: 0 auto;
  padding: 2rem;
}

h1 {
  font-size: 1.8rem;
  color: #1f2937;
  margin-bottom: 2rem;
}

.tabs {
  display: flex;
  border-bottom: 1px solid #e5e7eb;
  margin-bottom: 2rem;
}

.tab-btn {
  padding: 0.75rem 1.5rem;
  background: none;
  border: none;
  border-bottom: 2px solid transparent;
  font-size: 1rem;
  font-weight: 500;
  color: #6b7280;
  cursor: pointer;
  transition: all 0.2s;
}

.tab-btn:hover {
  color: #3b82f6;
}

.tab-btn.active {
  color: #3b82f6;
  border-bottom-color: #3b82f6;
}

.transactions-list {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.transaction-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.transaction-header {
  display: flex;
  justify-content: space-between;
  padding: 1rem;
  background-color: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
}

.transaction-id {
  font-size: 0.9rem;
  color: #6b7280;
}

.transaction-status {
  font-weight: 500;
  font-size: 0.9rem;
}

.transaction-status.pending {
  color: #f59e0b;
}

.transaction-status.completed {
  color: #10b981;
}

.transaction-status.cancelled {
  color: #ef4444;
}

.transaction-content {
  padding: 1.5rem;
}

.transaction-details {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
  margin-bottom: 1.5rem;
  padding: 1rem;
  background-color: #f9fafb;
  border-radius: 8px;
}

.detail-item {
  display: flex;
  flex-direction: column;
}

.detail-item .label {
  color: #6b7280;
  font-size: 0.9rem;
  margin-bottom: 0.25rem;
}

.transaction-actions {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
  justify-content: flex-end;
  margin-top: 1.5rem;
}

.btn-confirm, .btn-cancel, .btn-rate, .btn-detail {
  padding: 0.5rem 1rem;
  border-radius: 4px;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-confirm {
  background-color: #10b981;
  color: white;
  border: none;
}

.btn-confirm:hover {
  background-color: #059669;
}

.btn-cancel {
  background-color: #f3f4f6;
  color: #ef4444;
  border: 1px solid #ef4444;
}

.btn-cancel:hover {
  background-color: #fee2e2;
}

.btn-rate, .btn-detail {
  background-color: #3b82f6;
  color: white;
  border: none;
}

.btn-rate:hover, .btn-detail:hover {
  background-color: #2563eb;
}

.empty-state {
  text-align: center;
  padding: 4rem 2rem;
  background-color: #f9fafb;
  border-radius: 8px;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.empty-state h3 {
  margin-bottom: 1rem;
  color: #1f2937;
}

.empty-state p {
  color: #6b7280;
  margin-bottom: 1.5rem;
}

.btn-browse {
  display: inline-block;
  padding: 0.75rem 1.5rem;
  background-color: #3b82f6;
  color: white;
  border-radius: 4px;
  text-decoration: none;
  font-weight: 500;
}

.btn-browse:hover {
  background-color: #2563eb;
}

.rating-modal, .order-detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h3 {
  margin: 0;
  color: #1f2937;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #6b7280;
}

.modal-body {
  padding: 1.5rem;
}

.rating-book-info {
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px dashed #e5e7eb;
}

.rating-book-info h4 {
  margin: 0 0 0.5rem;
  color: #1f2937;
}

.rating-stars {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.stars-container {
  display: flex;
}

.star {
  font-size: 1.8rem;
  color: #d1d5db;
  cursor: pointer;
}

.star.active {
  color: #f59e0b;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #4b5563;
  font-weight: 500;
}

.form-group textarea {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  resize: vertical;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

.btn-submit {
  padding: 0.5rem 1.5rem;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
}

.btn-submit:hover {
  background-color: #2563eb;
}

/* 订单详情样式 */
.order-detail-content {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.order-book-item {
  padding: 1rem;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  background-color: #f9fafb;
}

.order-book-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.order-book-header h4 {
  margin: 0;
  font-size: 1.1rem;
  color: #1f2937;
}

.order-book-price {
  font-weight: bold;
  font-size: 1.1rem;
  color: #ef4444;
}

.order-book-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0.75rem;
}

.info-item {
  display: flex;
  flex-direction: column;
}

.info-item .label {
  color: #6b7280;
  font-size: 0.85rem;
  margin-bottom: 0.25rem;
}

.empty-order-detail {
  text-align: center;
  padding: 2rem;
  color: #6b7280;
}

/* 支付模态框样式 */
.payment-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.payment-order-info {
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px dashed #e5e7eb;
}

.payment-order-info h4 {
  margin: 0 0 0.5rem;
  color: #1f2937;
}

.payment-amount {
  font-size: 1.5rem;
  font-weight: bold;
  color: #ef4444;
  margin-top: 0.5rem;
}

.payment-methods {
  margin-bottom: 1.5rem;
}

.payment-methods h4 {
  margin-bottom: 1rem;
  color: #1f2937;
}

.payment-method-options {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
}

.payment-method-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 1rem;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  width: 120px;
}

.payment-method-option:hover {
  border-color: #3b82f6;
  background-color: #f0f9ff;
}

.payment-method-option.active {
  border-color: #3b82f6;
  background-color: #eff6ff;
}

.payment-icon {
  width: 40px;
  height: 40px;
  margin-bottom: 0.5rem;
  object-fit: contain;
}

.payment-remark {
  margin-bottom: 1.5rem;
}

.payment-remark h4 {
  margin-bottom: 0.5rem;
  color: #1f2937;
}

.payment-remark textarea {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  resize: vertical;
}

.payment-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

.btn-pay-submit {
  padding: 0.75rem 1.5rem;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
}

.btn-pay-submit:hover {
  background-color: #2563eb;
}

.btn-pay-submit:disabled {
  background-color: #9ca3af;
  cursor: not-allowed;
}

.btn-pay-cancel {
  padding: 0.75rem 1.5rem;
  background-color: #f3f4f6;
  color: #4b5563;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
}

.btn-pay-cancel:hover {
  background-color: #e5e7eb;
}

/* 取消订单确认模态框样式 */
.cancel-confirm-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.cancel-warning {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1rem;
  padding: 1rem;
  background-color: #fee2e2;
  border-radius: 6px;
}

.cancel-warning .el-icon {
  font-size: 1.5rem;
  color: #ef4444;
}

.cancel-warning p {
  margin: 0;
  font-weight: 500;
  color: #b91c1c;
}

.order-id-highlight {
  font-weight: bold;
}

.cancel-notice {
  color: #6b7280;
  margin-bottom: 1.5rem;
}

.cancel-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

.btn-confirm-cancel {
  padding: 0.75rem 1.5rem;
  background-color: #ef4444;
  color: white;
  border: none;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
}

.btn-confirm-cancel:hover {
  background-color: #dc2626;
}

.btn-abort-cancel {
  padding: 0.75rem 1.5rem;
  background-color: #f3f4f6;
  color: #4b5563;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
}

.btn-abort-cancel:hover {
  background-color: #e5e7eb;
}

/* 查看评价按钮样式 */
.btn-view-rate {
  padding: 0.5rem 1rem;
  border-radius: 4px;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  background-color: #6366f1;
  color: white;
  border: none;
}

.btn-view-rate:hover {
  background-color: #4f46e5;
}

/* 评价查看模态框样式 */
.rating-view-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.rating-detail {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.rating-stars-display {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.rating-comment-box {
  background-color: #f9fafb;
  padding: 1rem;
  border-radius: 6px;
  border: 1px solid #e5e7eb;
}

.rating-comment-box h4 {
  margin-top: 0;
  margin-bottom: 0.5rem;
  color: #4b5563;
}

.rating-comment-box p {
  margin: 0;
  color: #1f2937;
  white-space: pre-wrap;
}

.rating-metadata {
  font-size: 0.85rem;
  color: #6b7280;
  text-align: right;
}

.empty-rating {
  text-align: center;
  padding: 2rem;
  color: #6b7280;
  background-color: #f9fafb;
  border-radius: 6px;
}

@media (max-width: 768px) {
  .container {
    padding: 1rem;
  }
  
  .transaction-details {
    grid-template-columns: 1fr;
  }
  
  .transaction-actions {
    justify-content: center;
  }
  
  .tabs {
    overflow-x: auto;
    padding-bottom: 0.5rem;
  }
  
  .tab-btn {
    padding: 0.75rem 1rem;
    white-space: nowrap;
  }
  
  .order-book-info {
    grid-template-columns: 1fr;
  }
  
  .payment-method-options {
    justify-content: center;
  }
}
</style> 